`
https://leetcode.cn/problems/longest-common-subsequence/
`

/**
 * @param {string} text1
 * @param {string} text2
 * @return {string}
 */
var longestCommonSubsequence = function (text1, text2) {
  const m = text1.length, n = text2.length

  // dp[i][j] 表示 text1[0...i-1] 和 text2[0...j-1] 的 lcs 长度
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0))

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (text1[i - 1] === text2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
      }
    }
  }

  // 回溯构造 lcs 字符串
  let i = m, j = n
  let lcs = ''
  while (i > 0 && j > 0) {
    if (text1[i - 1] === text2[j - 1]) {
      lcs = text1[i - 1] + lcs // 当前字符在 lcs 中
      i--
      j--
    } else if (dp[i - 1][j] > dp[i][j - 1]) {
      i-- // 向上移动
    } else {
      j-- // 向左移动
    }
  }

  return lcs
};

// test
const text1 = "abcde"
const text2 = "ace"
console.log(longestCommonSubsequence(text1, text2)) // "ace"